package com.heima.user.service.Impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    StringRedisTemplate redisTemplate; // key  value都使用字符串序列化



    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1.检验参数（是否登录 判断operation: 0   1）
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //登录用户id
        Integer loginUserId = user.getId();
        //作者用户id
        Integer authorUserId = dto.getAuthorApUserId();


        Short operation = dto.getOperation();
        if (operation.intValue() == 0){
            //2.如果operation为0   代表执行关注操作
                //2.1判断登录用户  是否已经关注过作者用户
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorUserId));
            if (score != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复关注");
            }
                //2.2判断登录用户  和 作者用户是否是同一个用户
            if (loginUserId.equals(authorUserId)){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿自己关注自己");
            }
                //2.3在登录用户的关注集合中  加入作者用户id
            redisTemplate.opsForZSet().add(
                    UserRelationConstants.FOLLOW_LIST+loginUserId,
                    String.valueOf(authorUserId),
                    System.currentTimeMillis()
            );
                //2.4在作者用户的粉丝集合中 加入登录用户id
            redisTemplate.opsForZSet().add(
                    UserRelationConstants.FANS_LIST+authorUserId,
                    String.valueOf(loginUserId),
                    System.currentTimeMillis()
            );
        }else {
            //3.如果operation为1  代表执行取关操作
                //3.1在登录用户的关注集合中  删除作者用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST+loginUserId,String.valueOf(authorUserId));
                //3.2在作者用户的粉丝集合中 删除登录用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST+authorUserId,String.valueOf(loginUserId));
        }
      return ResponseResult.okResult();
    }
}
